package com.yunlong.util;


import com.baidubce.auth.DefaultBceCredentials;
import com.baidubce.services.bos.BosClient;
import com.baidubce.services.bos.BosClientConfiguration;
import com.baidubce.services.bos.model.ObjectMetadata;
import com.baidubce.services.bos.model.PutObjectResponse;
import com.yunlong.wrapper.ResultWrapper;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import java.awt.*;
import java.io.*;
import java.util.UUID;

/**
 * @author guorui
 * @date 2021-07-17 11:37
 * 简单上传object，包括以文件、数据流、二进制串、字符串方式；上传时设置object元信息的demo
 */
public class PutObjectDemo {
    /**
     * 用户的Access Key ID
     */
    static String ACCESS_KEY_ID = "c3b64d27a7e64cb8a841021fe35101de";
    /**
     * 用户的Secret Access Key
     */
    static String SECRET_ACCESS_KEY = "ebb2091a6ac34052acaab2a315021848";
    /**
     * 用户自己指定的域名,参考说明文档,保定
     */
    static String ENDPOINT = "yundingstudents.bd.bcebos.com";
    /**
     * 简单上传，支持以指定文件形式、以数据流方式、以二进制串方式、以字符串方式执行Object上传
     */

    public static ResultWrapper putObjectSimple(MultipartFile file0, String userId) throws IOException {
        // 初始化一个BosClient
        BosClientConfiguration config = new BosClientConfiguration();
//        使用AK/SK新建BosClient
//        BosClientConfiguration是BOS服务的配置类，可以为客户端配置代理，最大连接数等参数。
        config.setCredentials(new DefaultBceCredentials(ACCESS_KEY_ID, SECRET_ACCESS_KEY));
        //最大连接数15
        config.setMaxConnections(15);
        config.setEndpoint(ENDPOINT);
        BosClient client = new BosClient(config);
        File file = tranFile(file0);
        // 获取指定文件
//        File file = new File("E:\\李国瑞\\太原理工大学\\评奖推优\\myself.jpg");
        // 获取数据流
//        InputStream inputStream = new FileInputStream("E:\\胡班人员信息.xlsx");
//        byte[] byte0 = new byte[0];
        String fileName = file.getName();
        String prefix = fileName.substring(fileName.lastIndexOf("."));
        // 以文件形式上传Object
        //key是文件名
        //如果上传的是简历，则存入resume中，否则则是图片，存入image文件夹中
        if(prefix.equals(".docx")){
            PutObjectResponse putObjectFromFileResponse =
                    client.putObject("resume", userId+prefix, file);
            client.shutdown();
            return ResultWrapper.success("上传成功");
        }else{
            boolean flag = isImage(file);
            if(flag==false){
                client.shutdown();
                return ResultWrapper.failure("图片格式必须为.jpg，请重新上传");
            }
            PutObjectResponse putObjectFromFileResponse =
                    client.putObject("image", userId+prefix, file);
            client.shutdown();
            return ResultWrapper.successWithData("https://yundingstudents.bd.bcebos.com/image/"+userId+prefix);
        }
//        // 以数据流形式上传Object
//        PutObjectResponse putObjectResponseFromInputStream =
//                client.putObject("bucketName", "inputStream-objectKey", inputStream);
//        // 以二进制串上传Object
//        PutObjectResponse putObjectResponseFromByte =
//                client.putObject("bucketName", "byte-objectKey", byte0);
//        // 以字符串上传Object
//        PutObjectResponse putObjectResponseFromString =
//                client.putObject("bucketName", "string-objectKey", "hello world");
        // 关闭客户端
    }

    // 上传object时设置文件元信息meta
    public static void putObjectWithMeta() {
        String ACCESS_KEY_ID = "c3b64d27a7e64cb8a841021fe35101de";             // 用户的Access Key ID
        String SECRET_ACCESS_KEY = "ebb2091a6ac34052acaab2a315021848";         // 用户的Secret Access Key
        String ENDPOINT = "yundingstudents.bd.bcebos.com";                                     // 用户自己指定的域名，参考说明文档,保定

        // 初始化一个BosClient
        BosClientConfiguration config = new BosClientConfiguration();
        config.setCredentials(new DefaultBceCredentials(ACCESS_KEY_ID, SECRET_ACCESS_KEY));
        config.setEndpoint(ENDPOINT);
        BosClient client = new BosClient(config);

        // 获取指定文件
        File file = new File("E:\\李国瑞\\太原理工大学\\评奖推优\\myself.jpg");

        // 初始化上传输入流
        ObjectMetadata meta = new ObjectMetadata();
        // 设置ContentLength大小
//        meta.setContentLength(1000);
        // 设置ContentType application/msword word文档
        //
        meta.setContentType("image/jpg;utf-8");
        // 设置cache-control
        meta.setCacheControl("no-cache");
        // 设置x-bce-content-crc32
        meta.setxBceCrc("crc");

        // 设置自定义元数据name的值为my-data
        meta.addUserMetadata("name", "my-data");

        // 上传Object
        client.putObject("test", "lgr.jpg", file, meta);

        // 关闭客户端
        client.shutdown();
    }
    public static File tranFile(MultipartFile file) throws IOException {
        String fileName = file.getOriginalFilename();
        String prefix = fileName.substring(fileName.lastIndexOf("."));
        String uuidTemp = UUID.randomUUID().toString();
        String uuid = uuidTemp.replace("-", "");
        File imageFile = File.createTempFile(uuid, prefix);
        file.transferTo(imageFile);
        return imageFile;
    }
    /**
     * 通过读取文件并获取其width及height的方式，来判断判断当前文件是否图片，这是一种非常简单的方式。
     *
     * @param imageFile
     * @return
     */
    public static boolean isImage(File imageFile) {
        if (!imageFile.exists()) {
            return false;
        }
        Image img = null;
        try {
            img = ImageIO.read(imageFile);
            if (img == null || img.getWidth(null) <= 0 || img.getHeight(null) <= 0) {
                return false;
            }
            return true;
        } catch (Exception e) {
            return false;
        }finally {
            img=null;
        }
    }

    public static void main(String[] args) throws FileNotFoundException {
//        PutObjectDemo putObjectDemo = new PutObjectDemo();
//        PutObjectDemo.putObjectSimple();
        String fileName = "asdfg.css";
        String prefix = fileName.substring(fileName.lastIndexOf("."));
        System.out.println(prefix);
    }

}